package com.shujia.scala

import scala.io.Source

object Demo24Student {
  def main(args: Array[String]): Unit = {

    /**
      *
      * 统计每一个班级的平均年龄
      *
      */

    //1、读取文件
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList


    //2、取出班级和年龄
    val clazzAndAge: List[(String, Double)] = students.map(student => {
      //取出班级和年龄
      val split: Array[String] = student.split(",")
      val age: Double = split(2).toDouble
      val clazz: String = split(4)

      (clazz, age)
    })

    //3、按照班级分组
    val groupBy: Map[String, List[(String, Double)]] = clazzAndAge.groupBy(kv => kv._1)


    //4、统计平均年龄
    val clazzAvgAge: Map[String, Double] = groupBy.map(kv => {
      //班级
      val clazz: String = kv._1

      //一个班级所有的数据
      val values: List[(String, Double)] = kv._2

      //取出年龄
      val ages: List[Double] = values.map(ca => ca._2)

      //九三平均值
      val avgAge: Double = ages.sum / ages.length

      (clazz, avgAge)
    })

    clazzAvgAge.foreach(println)

  }

}
